<template>
	<div class="search">
		<Row>
			<Col>
			<Card>
				<Row @keydown.enter.native="handleSearch">
					<Form ref="searchForm" :model="searchForm" inline :label-width="110" class="search-form">
						<Form-item label="视频标题" prop="title">
							<Input type="text" v-model.trim="searchForm.title" placeholder="请输入标题" clearable style="width: 200px" />
						</Form-item>

						<Form-item style="margin-left:-35px;" class="br">
							<Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
							<Button @click="handleReset">重置</Button>

						</Form-item>
					</Form>
				</Row>
				<Row class="operation">
					<Button @click="add" type="primary" icon="md-add">添加</Button>
					<Button @click="delAll" icon="md-trash">批量删除</Button>
					<Button @click="getDataList" icon="md-refresh">刷新</Button>
					<circleLoading v-if="operationLoading" />
				</Row>
				<Row>
					<Alert show-icon>
						已选择 <span class="select-count">{{selectCount}}</span> 项
						<a class="select-clear" @click="clearSelectAll">清空</a>
					</Alert>
				</Row>
				<Row>
					<Table :loading="loading" border :columns="columns" :data="data" ref="table" sortable="custom" @on-sort-change="changeSort"
					 @on-selection-change="changeSelect"></Table>
				</Row>
				<Row type="flex" justify="end" class="page">
					<Page :current="pageNumber" :total="total" :page-size="pageSize" @on-change="changePage" @on-page-size-change="changePageSize"
					 :page-size-opts="[10,20,50]" size="small" show-total show-elevator show-sizer></Page>
				</Row>
			</Card>
			</Col>

		</Row>
		<Modal :title="modalTitle" v-model="modalVisible" :mask-closable='false' :width="600">
			<Form ref="form" :model="form" :label-width="100" :rules="formValidate">
				<FormItem label="标题" prop="title">
					<Input v-model.trim="form.title" :maxlength=50 placeholder="请输入标题" style="width:350px" />
				</FormItem>


				<FormItem label="封面图" prop="imageUrl">
					<Input v-model.trim="form.imageUrl" :maxlength=200 placeholder="请输入封面图链接" style="width:350px" @on-change="inputImage" />
					<Progress :percent="progressImage" v-show="progressImage>0" />
					<Row style="margin-top:10px;">
						<Col span="4">
						<Upload ref="uploadImage" :show-upload-list="false" :default-file-list="image.uploadList" :on-success="handleSuccessImage"
						 :on-progress="handleProgressImage"  :on-error="handleErrorImage" :format="['jpg','jpeg','png','gif']" :max-size="5120" :on-format-error="handleFormatErrorImage"
						 :on-exceeded-size="handleMaxSizeImage" :before-upload="handleBeforeUploadImage" type="drag" :action="uploadFileUrl"
						 :headers="accessToken" style="display: inline-block;width:58px;">
							<div style="width: 58px;height:58px;line-height: 58px;">
								<Icon type="md-camera" size="20"></Icon>
							</div>
						</Upload>
						</Col>
						<Col span="20">

						<div class="upload-list" v-for="item in image.uploadList" :key="item.url">
							<template>
								<img :src="item.url" style="width:200px;">
							</template>
						</div>
						</Col>
					</Row>
				</FormItem>
				<FormItem label="视频" prop="videoUrl">
					<Input v-model.trim="form.videoUrl" :maxlength=200 placeholder="请输入视频链接" style="width:350px" @on-change="inputVideo" />
					<Progress :percent="progressVideo" v-show="progressVideo>0" />
					<Row style="margin-top:10px;">
						<Col span="4">
						<Upload ref="uploadVideo" :show-upload-list="false" :default-file-list="video.uploadList" :on-success="handleSuccessVideo"
						 :on-progress="handleProgressVideo" :on-error="handleErrorVideo" :format="['mp4']" :max-size="20480"
						 :on-format-error="handleFormatErrorVideo" :on-exceeded-size="handleMaxSizeVideo" :before-upload="handleBeforeUploadVideo"
						 type="drag" :action="uploadFileUrl" :headers="accessToken" style="display: inline-block;width:58px;">
							<div style="width: 58px;height:58px;line-height: 58px;">
								<Icon type="md-camera" size="20"></Icon>
							</div>
						</Upload>
						</Col>
						<Col span="20">

						<div class="upload-list" v-for="item in video.uploadList" :key="item.url">
							<template>
								<video controls="controls" preload="auto" :src='item.url' style="width:200px;"></video>
							</template>
						</div>
						</Col>
					</Row>
				</FormItem>

				<FormItem label="推送首页" prop="pushHome">
					<i-switch size="large" v-model="form.pushHome">
						<span slot="open">是</span>
						<span slot="close">否</span>
					</i-switch>
				</FormItem>

				<FormItem label="排序值" prop="sortOrder">
					<InputNumber :max="1000" :min="0" v-model="form.sortOrder"></InputNumber>
					<span style="margin-left:5px">值越小越靠前，支持小数</span>
				</FormItem>
			</Form>
			<div slot="footer">
				<Button type="text" @click="modalVisible=false">取消</Button>
				<Button type="primary" :loading="submitLoading" @click="handleSubmit">提交</Button>
			</div>
		</Modal>
		<Modal v-model="image.preVisible" :title="image.preTitle" draggable footer-hide>
			<img :src="image.preUrl" alt="无效的图片链接" style="width: 100%;margin: 0 auto;display: block;">
		</Modal>
		<Modal v-model="video.preVisible" :title="video.preTitle" draggable footer-hide>
			<video controls="controls" preload="auto" :src='video.preUrl' style="width:100%;"></video>
		</Modal>
	</div>
</template>

<script>
	import circleLoading from "@/views/my-components/circle-loading.vue";

	import {
		addVideo,
		editVideo,
		getVideoList,
		deleteVideo,
		uploadFile,
		getAllMiniprogramPath,

	} from "@/api/index";
	export default {
		name: "video-manage",
		components: {
			circleLoading,
		},
		data() {
			return {
				progressImage: 0,
				progressVideo: 0, //上传视频进度条
				/*图片上传部分开始*/
				accessToken: {},
				uploadFileUrl: uploadFile,
				image: {
					uploadList: [],
					preVisible: false,
					preTitle: '',
					preUrl: '',
				},

				video: {
					uploadList: [],
					preVisible: false,
					preTitle: '',
					preUrl: '',
				},



				/*图片上传部分结束*/
				loading: true, // 表单加载状态
				operationLoading: false, // 操作加载状态
				modalType: 0, // 添加或编辑标识
				modalVisible: false, // 添加或编辑显示
				modalTitle: "", // 添加或编辑标题
				searchForm: { // 搜索框初始化对象
					pageNumber: 1, // 当前页数
					pageSize: 10, // 页面大小
					sort: '[{field:"pushHome", order: "asc"},{field:"sortOrder", order: "asc"}]'
				},
				form: { // 添加或编辑表单对象初始化数据
					title: "",
					sortOrder: 0,
					imageUrl: '',
					videoUrl: '',
					pushHome: false,
				},
				// 表单验证规则
				formValidate: {
					title: [{
						required: true,
						trigger: "blur",
						message: "请输入视频标题"
					}],
					imageUrl: [{
						required: true,
						trigger: "change",
						message: "请上传封面图"
					}],
					videoUrl: [{
						required: true,
						trigger: "change",
						message: "请上传视频"
					}],
					pushHome: [{
						type: 'boolean',
						required: true,
						trigger: "change",
						message: "请选择是否推送首页"
					}],

				},
				submitLoading: false, // 添加或编辑提交状态
				selectList: [], // 多选数据
				selectCount: 0, // 多选计数
				columns: [
					// 表头
					{
						type: "selection",
						width: 60,
						align: "center"
					},
					{
						type: "index",
						width: 60,
						align: "center"
					},
					{
						title: "标题",
						key: "title",
						minWidth: 120,
					},
					{
						title: "缩略图(点击预览)",
						key: "imageUrl",
						width: 130,
						align: "center",
						render: (h, params) => {

							return h("img", {
								attrs: {
									src: params.row.imageUrl,
									alt: "加载图片失败"
								},
								style: {
									cursor: "pointer",
									width: "80px",
									height: "60px",
									margin: "10px 0",
									"object-fit": "contain"
								},
								on: {
									click: () => {
										this.showImage(params.row);
									}
								}
							});

						}
					},
					{
						title: "视频",
						key: "videoUrl",
						width: 130,
						align: "center",
						render: (h, params) => {

							return h("div", {
								on: {
									click: () => {
										this.showVideo(params.row);
									}
								}
							}, '查看视频');

						}
					},
					{
						title: "推送首页",
						key: "pushHome",
						minWidth: 120,
						sortable: true,
						render: (h, params) => {
							return h("div", params.row.pushHome == true ? '是' : '否');

						}
					},
					{
						title: "排序值",
						key: "sortOrder",
						sortable: true,
						minWidth: 120,
					},
					{
						title: "创建时间",
						key: "createTime",
						minWidth: 160,
						sortable: true,
					},
					{
						title: "更新时间",
						key: "updateTime",
						minWidth: 160,
						sortable: true,
					},
					{
						title: "操作",
						key: "action",
						align: "center",
						width: 120,
						fixed: 'right',
						render: (h, params) => {
							return h("div", [
								h(
									'I', {
										class: 'ivu-icon ivu-icon-ios-create-outline',
										style: {
											marginRight: "5px",
											color: "#2d8cf0",
											'font-size': "28px",
											'font-weight': "bold",
											cursor: "pointer"
										},
										attrs: {
											title: "编辑",

										},

										on: {
											click: () => {
												this.edit(params.row);
											}
										}
									},

								),

								h(
									'i', {
										class: 'ivu-icon ivu-icon-ios-trash',
										style: {
											marginRight: "5px",
											color: "#ff5959",
											'font-size': "28px",
											cursor: "pointer"
										},
										attrs: {
											title: "删除",
										},

										on: {
											click: () => {
												this.remove(params.row);
											}
										}
									},

								)
							]);
						}
					}
				],
				data: [], // 表单数据
				pageNumber: 1, // 当前页数
				pageSize: 10, // 页面大小
				total: 0, // 表单数据总数

			};
		},
		methods: {

			init() {
				this.initMiniprogramPath();
				this.getDataList();

			},
			//手动输入 图片地址
			inputImage(e) {
				this.image.uploadList = [{
					url: this.form.imageUrl
				}];
			},
			//手动输入 视频地址
			inputVideo(e) {
				this.video.uploadList = [{
					url: this.form.videoUrl
				}];
			},
			initMiniprogramPath() {
				getAllMiniprogramPath().then(res => {
					if (res.success === true) {
						this.paths = res.result;
					}
				});
			},
			changePage(v) {
				this.searchForm.pageNumber = v;
				this.getDataList();
				this.clearSelectAll();
			},
			changePageSize(v) {
				this.searchForm.pageSize = v;
				this.getDataList();
			},
			handleSearch() {
				this.searchForm.pageNumber = 1;
				this.searchForm.pageSize = 10;
				this.getDataList();
			},
			handleReset() {
				this.$refs.searchForm.resetFields();
				this.searchForm.pageNumber = 1;
				this.searchForm.pageSize = 10;
				// 重新加载数据
				this.getDataList();
			},
			changeSort(e) {
				this.searchForm.sort = e.key;
				this.searchForm.order = e.order;
				if (e.order === "normal") {
					this.searchForm.order = "";
				}
				this.getDataList();
			},
			clearSelectAll() {
				this.$refs.table.selectAll(false);
			},
			changeSelect(e) {
				this.selectList = e;
				this.selectCount = e.length;
			},
			getDataList() {
				this.loading = true;
				getVideoList(this.searchForm).then(res => {
					this.loading = false;
					if (res.success === true) {
						this.data = res.result.content;
						this.total = res.result.totalElements;
					}
				});


			},


			handleSubmit() {

				this.$refs.form.validate(valid => {

					if (valid) {

						this.submitLoading = true;

						if (this.modalType === 0) {
							// 添加 避免编辑后传入id等数据 记得删除
							delete this.form.id;

							addVideo(this.form).then(res => {
								this.submitLoading = false;
								if (res.success == true) {
									this.$Message.success("操作成功");
									this.getDataList();
									this.modalVisible = false;

								}
							});

						} else {
							// 编辑
							editVideo(this.form).then(res => {
								this.submitLoading = false;
								if (res.success == true) {
									this.$Message.success("操作成功");
									this.getDataList();
									this.modalVisible = false;
								}
							});

						}
					}
				});
			},
			add() {
				if (this.$refs.uploadImage) {
					this.$refs.uploadImage.clearFiles();
				}
				if (this.$refs.uploadVideo) {
					this.$refs.uploadVideo.clearFiles();
				}
				this.image.uploadList = [];
				this.video.uploadList = [];
				this.modalType = 0;
				this.modalTitle = "添加";
				this.$refs.form.resetFields();
				delete this.form.id;
				this.modalVisible = true;
			},
			edit(v) {
				this.modalType = 1;
				this.modalTitle = "编辑";
				// 转换null为""
				for (let attr in v) {
					if (v[attr] === null) {
						v[attr] = "";
					}
				}
				let str = JSON.stringify(v);
				let data = JSON.parse(str);
				this.form = data;

				if (this.$refs.uploadImage) {
					this.$refs.uploadImage.clearFiles();
				}
				if (this.$refs.uploadVideo) {
					this.$refs.uploadVideo.clearFiles();
				}
				this.image.uploadList = [{
					url: data.imageUrl
				}];
				this.video.uploadList = [{
					url: data.videoUrl
				}];
				this.modalVisible = true;
			},
			remove(v) {
				this.$Modal.confirm({
					title: "确认删除",
					// 记得确认修改此处
					content: "您确认要删除 " + v.title + " ?",
					onOk: () => {
						// 删除
						this.operationLoading = true;
						deleteVideo(v.id).then(res => {
							this.operationLoading = false;
							if (res.success == true) {
								this.$Message.success("删除成功");
								this.getDataList();
							}
						});


					}
				});
			},
			delAll() {
				if (this.selectCount <= 0) {
					this.$Message.warning("您还未选择要删除的数据");
					return;
				}
				this.$Modal.confirm({
					title: "确认删除",
					content: "您确认要删除所选的 " + this.selectCount + " 条数据?",
					onOk: () => {
						let ids = "";
						this.selectList.forEach(function(e) {
							ids += e.id + ",";
						});
						ids = ids.substring(0, ids.length - 1);
						this.operationLoading = true;
						deleteVideo(ids).then(res => {
							this.operationLoading = false;
							if (res.success == true) {
								this.$Message.success("删除成功");
								this.clearSelectAll();
								this.getDataList();
							}
						});
					}
				});
			},
			//封面图部分
			showImage(v) {
				this.image.preTitle = v.title + "(" + v.imageUrl + ")";
				this.image.preVisible = true;
				this.image.preUrl = v.imageUrl;
			},
			handleSuccessImage(res, file) {
				if (res.success == true) {
					file.url = res.result;
					this.form.imageUrl = res.result;

					this.image.uploadList = [{
						url: res.result
					}];
					this.$refs.uploadImage.clearFiles();
				} else {
					this.$refs.uploadImage.clearFiles();
					this.$Message.error(res.message);
				}
				this.hideUploadLoading();
			},
			handleErrorImage(error, file, fileList) {
				this.hideUploadLoading();
				this.$Message.error(error.toString());

			},
			handleFormatErrorImage(file) {
				this.$Notice.warning({
					title: "不支持的文件格式",
					desc: "所选文件‘ " +
						file.name +
						" ’格式不正确, 请选择 .jpg .jpeg .png .gif格式文件"
				});
				this.hideUploadLoading();
			},
			handleMaxSizeImage(file) {
				this.$Notice.warning({
					title: "文件大小过大",
					desc: "所选文件‘ " + file.name + " ’大小过大, 不得超过 5M."
				});
				this.hideUploadLoading();
			},
			handleBeforeUploadImage() {
				const check = this.image.uploadList.length < 2;
				if (!check) {
					this.$Notice.warning({
						title: "最多只能上传 1 张图片"
					});
				} else {
					this.showUploadLoading();
				}
				return check;
			},
			handleProgressImage(event, file, fileList) {
				this.progressImage = parseInt(event.percent);
			},

			//视频部分
			showVideo(v) {
				this.video.preTitle = v.title + "(" + v.videoUrl + ")";
				this.video.preVisible = true;
				this.video.preUrl = v.videoUrl;
			},
			handleSuccessVideo(res, file) {
				if (res.success == true) {
					file.url = res.result;
					this.form.videoUrl = res.result;

					this.video.uploadList = [{
						url: res.result
					}];
					this.$refs.uploadVideo.clearFiles();
				} else {
					this.$refs.uploadVideo.clearFiles();
					this.$Message.error(res.message);
				}
				this.hideUploadLoading();
			},
			handleErrorVideo(error, file, fileList) {
				this.hideUploadLoading();
				this.$Message.error(error.toString());
			},
			handleFormatErrorVideo(file) {
				this.$Notice.warning({
					title: "不支持的文件格式",
					desc: "所选文件‘ " +
						file.name +
						" ’格式不正确, 请选择 .mp4格式文件"
				});
				this.hideUploadLoading();
			},
			handleMaxSizeVideo(file) {
				this.$Notice.warning({
					title: "文件大小过大",
					desc: "所选文件‘ " + file.name + " ’大小过大, 不得超过 20M."
				});
				this.hideUploadLoading();
			},
			handleBeforeUploadVideo() {
				const check = this.video.uploadList.length < 2;
				if (!check) {
					this.$Notice.warning({
						title: "最多只能上传 1 个视频"
					});
				} else {
					this.showUploadLoading();
				}
				return check;
			},
			handleProgressVideo(event, file, fileList) {
				this.progressVideo = parseInt(event.percent);
			},
			showUploadLoading() {
				this.$Spin.show({
					render: (h) => {
						return h('div', [
							h('Icon', {
								'class': 'demo-spin-icon-load',
								props: {
									type: 'ios-loading',
									size: 18
								}
							}),
							h('div', '上传中')
						])
					}
				});
			},
			hideUploadLoading() {
				this.$Spin.hide();
			}

		},
		computed: {},
		mounted() {
			this.accessToken = {
				accessToken: this.getStore("accessToken")
			};

			this.init();
		}
	};
</script>
<style lang="less">
	.search {
		.operation {
			margin-bottom: 2vh;
		}

		.select-count {
			font-size: 13px;
			font-weight: 600;
			color: #40a9ff;
		}

		.select-clear {
			margin-left: 10px;
		}

		.page {
			margin-top: 2vh;
		}

		.drop-down {
			font-size: 13px;
			margin-left: 5px;
		}
	}

	.must::before {
		content: '*';
		display: inline-block;
		margin-right: 4px;
		line-height: 1;
		font-family: SimSun;
		font-size: 12px;
		color: #ed4014;
	}

	.demo-spin-icon-load {
		animation: ani-demo-spin 1s linear infinite;
	}
</style>
